import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
const store = new Vuex.Store({
    state:{
        todoList:[
            {
                id:Math.random().toString(36).slice(2),
                content:'学习',
                isChecked:true
            },
            {
                id:Math.random().toString(36).slice(2),
                content:'睡觉',
                isChecked:true
            },
            {
                id:Math.random().toString(36).slice(2),
                content:'打豆豆',
                isChecked:true
            }
        ]
    },
    mutations:{
        //添加数据
        ADD_LIST(state,newList){
            state.todoList = [
                newList,
                ...state.todoList
            ];
        },
        //保存数据到本地
        SAVE_DATA(state){
            localStorage.setItem('todoList',JSON.stringify(state.todoList));
        },
        //更改数据状态
        CHANGE_DATA(state,obj){
            const {key,id,value} = obj;
            state.todoList.map(item=>{
                if(item.id === id){
                    item[key] = value;
                }
                return item;
            })
        },
        //根据指定id删除数据
        DELETE_LIST(state,id){
            state.todoList = state.todoList.filter(item=>{
                return item.id !== id;
            })
        },
        //删除所有数据
        DELETE_ALL(state){
            if(window.confirm('确定全部删除吗?')){
                state.todoList = [];
            }
        },
        SET_DATA(state,value){
            state.todoList = value;
        }
    },
    getters:{
        //计算完成的数量
        finished(state){
            return state.todoList.filter(item=>{
                return item.isChecked === true;
            }).length;
        },
        //计算总数量
        total(state){
            return state.todoList.length
        },

    }
})
export default store;